﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.IO;
using System.Runtime.Serialization;

namespace BBECServiceBusAdapter.Helper_Activities
{

    public sealed class LogDataContract : CodeActivity
    {
        // Define an activity input argument of type string
        public InArgument<Object> DataMessage { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            //ConstituentDataContract theData = context.GetValue(this.ConstituentData);
            Object theData = context.GetValue(this.DataMessage);
            String logFileName = "";
            String logPath = AppDomain.CurrentDomain.BaseDirectory; //Environment.CurrentDirectory;
            
            MemoryStream ms = new MemoryStream();
            
            DataContractSerializer serializer;
            

            //Serialize the Record object to a memory stream using DataContractSerializer.
            if (theData is ConstituentDataContract)
            {
                serializer = new DataContractSerializer(typeof(ConstituentDataContract));
                logFileName = "ConstituentDataContract.txt";
            }
            else
            {
                serializer = new DataContractSerializer(typeof(Object));
                logFileName = "UnknownType.txt";
            }

            serializer.WriteObject(ms, theData);


            FileStream outStream = new FileStream(logPath + "\\" + logFileName, FileMode.Append, FileAccess.Write, FileShare.Read);

            //FileStream outStream = File.OpenWrite("C:\\ConstituentDataContract.txt");

            //ms.WriteTo("REQUEST:" & DateTime.Now.ToLongDateString());

            AddText(outStream, String.Concat(DateTime.Now.ToShortDateString(), " ", DateTime.Now.ToShortTimeString(), Environment.NewLine));
            ms.WriteTo(outStream);
            AddText(outStream, Environment.NewLine);
            AddText(outStream, Environment.NewLine);

            outStream.Flush();


            outStream.Close();






            //System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(
        }


        
    private void AddText(FileStream fs , String value )
    {
        Byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }

    }
}
